import {
  _decorator,
  Component,
  Vec3,
  instantiate,
  director,
  Prefab,
  UITransform,
} from "cc";
const { ccclass, property } = _decorator;
import EventManager from "../Runtime/EventManager";
type RewardConfig = {
  type: string;
  weight: number;
  prefab: Prefab;
};

@ccclass("RewardManager")
export class RewardManager extends Component {
  private spawnInterval: number = 1;
  private timer: number = 0;
  private screenWidth: number = 0;

  @property({ type: [Prefab] })
  rewardPrefabs: Array<Prefab> = [];

  private rewardConfigs: RewardConfig[] = [
    { type: "Damage", weight: 20, prefab: this.rewardPrefabs[0] },
    { type: "MoreShoot", weight: 20, prefab: this.rewardPrefabs[1] },
    { type: "SpeedBullet", weight: 20, prefab: this.rewardPrefabs[2] },
  ];
  onLoad() {
    // EventManager.Instance.on("MoreShoot", this.moreShoot, this);
  }
  start() {
    const transform = this.node.getComponent(UITransform);
    const nodeWidth = transform.width;
    this.screenWidth = nodeWidth;
    this.rewardConfigs = [
      { type: "Damage", weight: 10, prefab: this.rewardPrefabs[0] },
      { type: "MoreShoot", weight: 80, prefab: this.rewardPrefabs[1] },
      { type: "SpeedBullet", weight: 20, prefab: this.rewardPrefabs[2] },
    ];
    this.init();
  }

  public init(configs?: Partial<RewardConfig>[]) {
    if (configs) {
      this.rewardConfigs = this.rewardConfigs.map((defaultConfig) => {
        const customConfig = configs.find((c) => c.type === defaultConfig.type);
        return customConfig
          ? { ...defaultConfig, ...customConfig }
          : defaultConfig;
      });
    }
  }

  update(deltaTime: number) {
    this.timer += deltaTime;
    if (this.timer >= this.spawnInterval) {
      this.generateReward();
      this.timer = 0;
    }
  }

  private getRandomPosition(): Vec3 {
    const transform = this.node.getComponent(UITransform);
    const screenHeight = transform.height;
    return new Vec3(Math.random() * 480 - 480 / 2, 380, 0);
  }

  public generateReward(eventType?: string) {
    if (!this.node.active) return;
    const totalWeight = this.rewardConfigs.reduce(
      (sum, c) => sum + c.weight,
      0
    );
    const random = Math.random() * totalWeight;

    let currentWeight = 0;
    for (const config of this.rewardConfigs) {
      currentWeight += config.weight;
      if (random <= currentWeight) {
        const reward = instantiate(config.prefab);
        reward.setPosition(this.getRandomPosition());
        this.node.addChild(reward);
        break;
      }
    }
  }

  public setSpawnInterval(interval: number) {
    this.spawnInterval = interval;
  }
}
